#include "esp_camera.h"
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>

const char* ssid = "CarCameraByZZM";
const char* password = "12345678";
WiFiServer server(1314);

unsigned char rx_data[2000];
unsigned char tx_data[2000];


#define PWM_IN1 12
#define PWM_IN2 13
#define PWM_IN3 15
#define PWM_IN4 14
#define CAR_LED  2
#define BUZZER   4


#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27

#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22


void startCameraServer();

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  Serial.println();

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  //init with high specs to pre-allocate larger buffers
  if(psramFound()){
    config.frame_size = FRAMESIZE_UXGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }

  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  //drop down frame size for higher initial frame rate
  sensor_t * s = esp_camera_sensor_get();
  s->set_framesize(s, FRAMESIZE_QVGA);

  ledcAttachPin(PWM_IN1, 2); // assign RGB led pins to channels
  ledcAttachPin(PWM_IN2, 3);
  ledcAttachPin(PWM_IN3, 4);
  ledcAttachPin(PWM_IN4, 5);

  ledcSetup(2, 1000, 8); // 12 kHz PWM, 8-bit resolution
  ledcSetup(3, 1000, 8);
  ledcSetup(4, 1000, 8);
  ledcSetup(5, 1000, 8);

  pinMode(CAR_LED, OUTPUT);
  pinMode(BUZZER, OUTPUT);
  digitalWrite(CAR_LED, HIGH);

  // You can remove the password parameter if you want the AP to be open.
  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.begin();

  startCameraServer();

  Serial.print("Camera Ready! Use 'http://");
  Serial.print(myIP);
  Serial.println("' to connect");
}


void close_all_output(void)
{
  digitalWrite(CAR_LED, LOW);
  digitalWrite(BUZZER, HIGH);
  ledcWrite(2, 0);
  ledcWrite(3, 0);
  ledcWrite(4, 0);
  ledcWrite(5, 0);
}

int recLenth;
int64_t fristTime;
int64_t lastTime;
int timeout;
int pwmDuty;

void loop() {
  // put your main code here, to run repeatedly:

  
  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("New Client.");           // print a message out the serial port
    while (client.connected()) {            // loop while the client's connected
      lastTime=esp_timer_get_time();
      timeout=(lastTime-fristTime)/1000;
      if(timeout>500)
      {
        close_all_output();
        fristTime=esp_timer_get_time();
        //Serial.printf("Rx timeout !!!\r\n");//debug
      }
      
      if (client.available()) {             // if there's bytes to read from the client,
        recLenth+=client.read(rx_data,8);
        if(recLenth>=8)
        {
          recLenth=0;
          if( (rx_data[0]==0x5a) && (rx_data[7]==0xa5) )
          {
            /*for(int i=0;i<8;i++)
            {
              Serial.printf("%d  ",rx_data[i]);
            }
             Serial.printf("\r\n");*///debug

            timeout=0;
            fristTime=esp_timer_get_time();
            pwmDuty=rx_data[1];
            if(pwmDuty<=100)//left motor
            {
              ledcWrite(2, 255*pwmDuty/100);
              ledcWrite(3, 0);
            }
            else 
            {
              ledcWrite(3, 255*(256-pwmDuty)/100);
              ledcWrite(2, 0);
            }
            pwmDuty=rx_data[2];
            if(pwmDuty<=100)//right motor
            {
              ledcWrite(5, 255*pwmDuty/100);
              ledcWrite(4, 0);
            }
            else 
            {
              ledcWrite(4, 255*(256-pwmDuty)/100);
              ledcWrite(5, 0);
            }  
            if(rx_data[3]&0x02)//CAR_LED
            {
              digitalWrite(CAR_LED, HIGH);
            }
            else
            {
              digitalWrite(CAR_LED, LOW);
            } 
            if(rx_data[3]&0x01)//CAR_BUZZER
            {
              digitalWrite(BUZZER, LOW);
            }
            else
            {
              digitalWrite(BUZZER, HIGH);
            }

            client.write(rx_data,8);
          }
        }   
      }
    }
  }
  close_all_output();
  delay(100);
}
